<template>
  <el-card
      shadow="never"
      :class="['resource-item-card', { 'is-clickable': navigationEnabled }]"
      @click="handleCardClick"
  >
    <div class="image-container">
      <el-image
          :src="resource.coverImage"
          fit="cover"
          class="resource-image"
          lazy
      >
        <template #error>
          <div class="image-slot">
            <el-icon><Picture /></el-icon>
          </div>
        </template>
      </el-image>

      <span
          v-if="resource.difficulty != null"
          :class="['difficulty-badge', `difficulty-${resource.difficulty}`]"
      >
        {{ formatDifficulty(resource.difficulty) }}
      </span>

      <div
          v-if="resource.category === 0 || resource.category === 1"
          class="category-icon-wrapper"
      >
        <el-icon>
          <Document v-if="resource.category === 0" />
          <VideoPlay v-if="resource.category === 1" />
        </el-icon>
      </div>
    </div>

    <div class="content-area">
      <h3 class="resource-title" :title="resource.title">{{ resource.title }}</h3>
      <div class="major-tag-wrapper" v-if="resource.major">
        <span class="major-tag">{{ resource.major }}</span>
      </div>
      <div class="bottom-info">
        <div class="author-info">
          <el-avatar :size="20" :src="resource.publisherAvatar" class="author-avatar" /> <span class="author-name">{{ resource.publisherName || '匿名' }}</span>
        </div>

        <div class="action-area">
          <el-button
              v-if="!isPurchased"
              class="redeem-button"
              size="small"
              type="primary"
              @click.stop="handleRedeem"
          >
            花费 {{ resource.credit || 0 }} 学分购买
          </el-button>
          <el-tag v-else type="success" class="purchased-tag" size="small" disable-transitions>
            已购买
          </el-tag>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { useRouter } from 'vue-router';
import {
  Picture,
  Document,
  VideoPlay,
} from '@element-plus/icons-vue';
import {
  ElCard,
  ElImage,
  ElIcon,
  ElAvatar,
  ElButton,
  ElMessageBox,
  ElMessage,
  ElTag
} from 'element-plus';
import creditService from '@/services/creditService';
import resourceService from '@/services/resourceService';
import { userManager } from '@/utils/user';
import { methods } from '@/utils/methods';
import {creditManager} from "@/utils/credit.js";

const props = defineProps({
  resource: {
    type: Object,
    required: true,
    default: () => ({
      id: '',
      title: '',
      coverImage: '',
      difficulty: null,
      category: null,
      major: '',
      publisherAvatar: '',
      publisherName: '',
      credit: 0
    })
  },
  isPurchased: {
    type: Boolean,
    default: false
  },
});

const emit = defineEmits(['redeem-success']);

const router = useRouter();

const difficultyTextMap = {
  0: '简单',
  1: '中等',
  2: '困难',
  3: '高阶',
};

function formatDifficulty(difficultyValue) {
  return difficultyTextMap[difficultyValue] || '未知';
}


function handleCardClick() {
  if (props.isPurchased) { //
    router.push(`/resource/${props.resource.id}`); //
  }
}

async function handleRedeem(e) {
  e.stopPropagation();

  const currentCredit = creditManager.getCurrentCredit();

  if (currentCredit == null || currentCredit < props.resource.credit) {
    ElMessage.error('您的学分不足，无法购买此资源！');
    return;
  }
  try {
    await ElMessageBox.confirm(
        `确定要花费 ${props.resource.credit} 学分购买 "${props.resource.title}" 吗？`,
        '确认购买',
        {
          confirmButtonText: '确认购买',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'redeem-confirm-dialog'
        }
    );

    const currentUserId = userManager.getUserId();
    if (!currentUserId) {
      ElMessage.error('请先登录再进行购买！');
      return;
    }

    creditService.addNewCredit(-props.resource.credit, null, methods.RESOURCE_PURCHASE, currentUserId, async (creditRes) => {
      if (creditRes.code === 1000) {
        try {
          const joinRes = await resourceService.joinResource(props.resource.id, currentUserId);
          if (joinRes.success) {
            ElMessage.success({
              message: '购买成功！资源已添加到您的账户',
              duration: 2000
            });
            emit('redeem-success', props.resource);
          } else {
            ElMessage.error(joinRes.message || '资源添加到仓库失败，但学分可能已被扣除，请联系管理员！');
          }
        } catch (joinError) {
          ElMessage.error('资源添加到仓库时发生网络错误，但学分可能已被扣除，请联系管理员！');
          console.error('加入资源失败:', joinError);
        }
      } else {
        ElMessage.error(creditRes.msg || '购买失败，请稍后重试');
      }
    });

  } catch (error) {
    if (error !== 'cancel') {
      console.log('购买流程出错', error);
    } else {
      console.log('用户取消购买');
    }
  }
}
</script>

<style scoped>
.resource-item-card {
  border-radius: 12px;
  border: 1px solid #e8eaed;
  overflow: hidden;
  position: relative;
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out, border-color 0.2s ease-in-out;
  background-color: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 【新增】当卡片可点击时，才应用鼠标指针和悬浮效果 */
.resource-item-card.is-clickable {
  cursor: pointer;
}

.resource-item-card.is-clickable:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 9px rgba(0,0,0,0.08);
  border-color: transparent;
}

.resource-item-card.is-clickable:hover .resource-image {
  transform: scale(1.05);
}


:deep(.el-card__body) {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.image-container {
  position: relative;
  width: 100%;
  height: 180px;
  overflow: hidden;
  background: #f5f7fa;
  flex-shrink: 0;
}

.resource-image {
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease;
  object-fit: cover;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
  font-size: 28px;
}

.content-area {
  padding: 12px;
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

.resource-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 38px;
}

.bottom-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.author-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.author-avatar {
  flex-shrink: 0;
  margin-right: 6px;
}

.author-name {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.major-tag-wrapper {
  margin-bottom: 12px;
}

.major-tag {
  display: inline-block;
  font-size: 11px;
  color: #1967d2;
  background-color: #e8f0fe;
  padding: 3px 8px;
  border-radius: 6px;
  border: 1px solid #d2e3fc;
}

.difficulty-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
  color: #fff;
  z-index: 10;
  box-shadow: 0 1px 3px rgba(0,0,0,0.2);
  border: 1px solid rgba(255,255,255,0.2);
  text-shadow: 1px 1px 2px rgba(0,0,0,0.3);
}

.difficulty-0 { background: linear-gradient(135deg, #67c23a, #85ce61); }
.difficulty-1 { background: linear-gradient(135deg, #409eff, #79bbff); }
.difficulty-2 { background: linear-gradient(135deg, #e6a23c, #ebb563); }
.difficulty-3 { background: linear-gradient(135deg, #f56c6c, #f89898); }

.category-icon-wrapper {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 28px;
  height: 28px;
  background-color: rgba(0, 0, 0, 0.4);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-size: 16px;
  z-index: 10;
}

.action-area {
  margin-left: 8px;
  flex-shrink: 0;
}

.redeem-button {
  font-size: 12px;
  padding: 5px 10px;
  border-radius: 6px;
  background: linear-gradient(135deg, #409eff, #79bbff);
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.redeem-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.purchased-tag {
  font-weight: 500;
  border: none;
  background-color: #f0f9eb;
  color: #67c23a;
}
</style>